

#import "Util.h"

#import "UIColor+Customer.h"
#import "ZXNotificationManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>



#define     Alert_TIPS                  @"温馨提示"
#define     Aler_Title_SURE             @"确定"
#define     Aler_Title_CANCEL           @"取消"

#define      Alertno_camera              @"您的设备没有照相机!"
#define      Alert_have_no_cameraAccess  @"请在iPhone的\"设置-隐私-相机\"中允许访问相机。"
#define      Alert_have_no_libraryAccess @"请在iPhone的\"设置-隐私-相册\"中允许访问相册。"

static NSInteger const k_Photo_Libary_Tag_Key = 8001;
static NSInteger const k_Camera_Tag_Key       = 8002;

typedef void(^RETRUMRESULTBLOCK)();

@interface Util ()

@property (copy,nonatomic)RETRUMRESULTBLOCK retrunResultBlock;

@end

@implementation Util

//用户隐私显示隐藏 1身份证 全部隐藏  2房产证，不动产，字号 展示后四位  3姓名  只展示最后一个   4公司名  第四第五展示星星 5办文
+(NSString *)privacyManageString:(NSString *)str andType:(int)type
{
    NSLog(@"iuadsgfiuo :%@",str);
    if (NULLString(str)||[str isEqualToString:@""]) {
        return @"";
    }else
    {
        NSMutableString * mStr = [str mutableCopy];
        if (type == 1) {
            for (int i = 0; i<mStr.length; i++) {
                //截取字符串中的每一个字符
                
                NSRange range = NSMakeRange(i, 1);
                //将字符串中的“m”转化为“w”
                 [[mStr stringByReplacingCharactersInRange:range withString:@"*"] copy];
            }
            return mStr;
            
        }else if (type == 2) {
            if (mStr.length>4) {
                for (int i = 0; i<mStr.length; i++) {
                    //截取字符串中的每一个字符
                    if (i<mStr.length-4) {
                        NSRange range = NSMakeRange(i, 1);
                        [mStr replaceCharactersInRange:range withString:@"*"];
                    }
                    
                }
               
               return [mStr copy];
            }else
            {
                return str;
            }
        }else if (type == 3) {
            if (mStr.length>1) {
                NSLog(@"iuadsgfiuo :%lu",(unsigned long)mStr.length);
                for (int i = 0; i<mStr.length; i++) {
                    //截取字符串中的每一个字符
                    if (i<mStr.length-1) {
                        NSRange range = NSMakeRange(i, 1);
                        [mStr replaceCharactersInRange:range withString:@"*"];
                    }
                    
                }
                
                return [mStr copy];
            }else
            {
                return str;
            }
        }else if (type == 4) {
            if (mStr.length>3) {
                if (mStr.length>=5) {
                    for (int i = 0; i<mStr.length; i++) {
                        //截取字符串中的每一个字符
                        if (i==3||i==4) {
                            NSRange range = NSMakeRange(i, 1);
                            [mStr replaceCharactersInRange:range withString:@"*"];
                        }
                        
                    }
                    
                    return [mStr copy];
                }else
                {
                    
                    [mStr replaceCharactersInRange:NSMakeRange(3, 1) withString:@"*"];
                    return [mStr copy];
                }
            }else
            {
                return str;
            }
        }else if (type == 5) {
            if (mStr.length>7) {
                
                for (int i = 0; i<mStr.length; i++) {
                    //截取字符串中的每一个字符
                    if (i>2&&i<mStr.length-4) {
                        NSRange range = NSMakeRange(i, 1);
                        [mStr replaceCharactersInRange:range withString:@"*"];
                    }
                    
                }
                
                    return [mStr copy];
                
            }else
            {
                return str;
            }
        }else
        {
            return str;
        }
    }
    
}

+(NSString *)quanToban:(NSString *)string
{
    NSMutableString *convertedString = [string mutableCopy];
    
    CFStringTransform((CFMutableStringRef)convertedString, NULL, kCFStringTransformFullwidthHalfwidth, false);
    return [convertedString copy];
}

+ (Util*)sharedUIFactory{
    
    static Util *factory = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        factory = [Util new];
    });
    return factory;
}



#pragma mark - 快捷创建UI AlertView
//AlertView
+ (UIAlertView *)createAlertViewWithMessage:(NSString *)message
{
    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:Alert_TIPS
                                                     message:message
                                                    delegate:nil
                                           cancelButtonTitle:Aler_Title_SURE
                                           otherButtonTitles:nil,nil];
    [alertV show];
    
    return alertV;
}
+ (UIAlertView *)createAlertViewWithMessage:(NSString *)message
                                     cancel:(NSString *)cancel
                                       sure:(NSString *)sure
                                        tag:(NSInteger)tag
                                   delegate:(id)delegate
{
    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:Alert_TIPS
                                                     message:message
                                                    delegate:delegate
                                           cancelButtonTitle:cancel
                                           otherButtonTitles:sure,nil];
    alertV.tag = tag;
    [alertV show];
    
    return alertV;
}

+ (UIAlertView *)createAlertViewWithTitle:(NSString *)title
                                  message:(NSString *)message
                                   cancel:(NSString *)cancel
                                     sure:(NSString *)sure
                                      tag:(NSInteger)tag
                                 delegate:(id)delegate
{
    NSString *myTitle = title;
    if (title.length == 0) {
        myTitle = Alert_TIPS;
    }
    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:myTitle
                                                     message:message
                                                    delegate:delegate
                                           cancelButtonTitle:cancel
                                           otherButtonTitles:sure,nil];
    alertV.tag = tag;
    [alertV show];
    
    return alertV;
}

//精确的身份证号码有效性检测
+ (BOOL)accurateVerifyIDCardNumber:(NSString *)sPaperId {
    NSString *carid = sPaperId;
    long lSumQT = 0 ;
    //加权因子
    int R[] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
    //校验码
    unsigned char sChecker[11] = {'1','0','X','9','8','7','6','5','4','3','2'};
    //将15位身份证号转换为18位
    NSMutableString *mString = [NSMutableString stringWithString:sPaperId];
    if (sPaperId.length == 15) {
        [mString insertString:@"19" atIndex:6];
        long p =0;
        //        const char *pid = [mString UTF8String];
        for (int i =0; i<17; i++)
        {
            NSString * s = [mString substringWithRange:NSMakeRange(i, 1)];
            p += [s intValue] * R[i];
            //            p += (long)(pid-48) * R;//
            
        }
        int o = p%11;
        NSString *string_content = [NSString stringWithFormat:@"%c",sChecker[o]];
        [mString insertString:string_content atIndex:[mString length]];
        carid = mString;
    }
    //判断地区码
    NSString *sProvince = [carid substringToIndex:2];
    NSLog(@"sProvince = %@",sProvince);
    if (![self isAreaCode:sProvince]) {
        return NO ;
    }
    //判断年月日是否有效
    //年份
    int strYear = [[Util getStringWithRange:carid Value1:6 Value2:4] intValue];
    //月份
    int strMonth = [[Util getStringWithRange:carid Value1:10 Value2:2] intValue];
    //日
    int strDay = [[Util getStringWithRange:carid Value1:12 Value2:2] intValue];
    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setTimeZone:localZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d 12:01:01",strYear,strMonth,strDay]];
    if (date == nil) {
        return NO;
    }
    [carid uppercaseString];
    const char *PaperId = [carid UTF8String];
    //检验长度
    if (18!=strlen(PaperId)) {
        return NO;
    }
    //校验数字
    NSString * lst = [carid substringFromIndex:carid.length-1];
    char di = [carid characterAtIndex:carid.length-1];
    
    if (!isdigit(di)) {
        if ([lst isEqualToString:@"X"]) {
        }else{
            return NO;
        }
    }
    //验证最末的校验码
    lSumQT = 0;
    for (int i = 0; i<17; i++){
        NSString * s = [carid substringWithRange:NSMakeRange(i, 1)];
        lSumQT += [s intValue] * R[i];
    }
    if (sChecker[lSumQT%11] != PaperId[17]) {
        return NO;
    }
    return YES;
}
+ (NSArray *)provinceArr {
    NSArray *pArr = @[
                      
                      @"11",//北京市|110000，
                      
                      @"12",//天津市|120000，
                      
                      @"13",//河北省|130000，
                      
                      @"14",//山西省|140000，
                      
                      @"15",//内蒙古自治区|150000，
                      
                      @"21",//辽宁省|210000，
                      
                      @"22",//吉林省|220000，
                      
                      @"23",//黑龙江省|230000，
                      
                      @"31",//上海市|310000，
                      
                      @"32",//江苏省|320000，
                      
                      @"33",//浙江省|330000，
                      
                      @"34",//安徽省|340000，
                      
                      @"35",//福建省|350000，
                      
                      @"36",//江西省|360000，
                      
                      @"37",//山东省|370000，
                      
                      @"41",//河南省|410000，
                      
                      @"42",//湖北省|420000，
                      
                      @"43",//湖南省|430000，
                      
                      @"44",//广东省|440000，
                      
                      @"45",//广西壮族自治区|450000，
                      
                      @"46",//海南省|460000，
                      
                      @"50",//重庆市|500000，
                      
                      @"51",//四川省|510000，
                      
                      @"52",//贵州省|520000，
                      
                      @"53",//云南省|530000，
                      
                      @"54",//西藏自治区|540000，
                      
                      @"61",//陕西省|610000，
                      
                      @"62",//甘肃省|620000，
                      
                      @"63",//青海省|630000，
                      
                      @"64",//宁夏回族自治区|640000，
                      
                      @"65",//新疆维吾尔自治区|650000，
                      
                      @"71",//台湾省（886)|710000,
                      
                      @"81",//香港特别行政区（852)|810000，
                      
                      @"82",//澳门特别行政区（853)|820000
                      
                      @"91",//国外
                      ];
    return pArr;
}

+ (BOOL)isAreaCode:(NSString *)province {
    //在provinceArr中找
    NSArray * arr = [Util provinceArr];
    int a = 0;
    for (NSString * pr in arr) {
        if ([pr isEqualToString:province]) {
            a ++;
        }
    }
    if (a == 0) {
        return NO;
    } else {
        return YES;
    }
}

+ (NSString *)getStringWithRange:(NSString *)str Value1:(int)v1 Value2:(int)v2 {
    NSString * sub = [str substringWithRange:NSMakeRange(v1, v2)];
    return sub;
}
#pragma mark - 便捷方法 限制 格式


+ (BOOL)verifyIDCardNumber:(NSString *)IDCardNumber
{
    IDCardNumber = [IDCardNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([IDCardNumber length] != 18)
    {
        return NO;
    }
    NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString *leapMmdd = @"0229";
    NSString *year = @"(19|20)[0-9]{2}";
    NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd , @"[0-9]{3}[0-9Xx]"];
    
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];if (![regexTest evaluateWithObject:IDCardNumber]){    return NO;}int summary = ([IDCardNumber substringWithRange:NSMakeRange(0,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(10,1)].intValue) *7+ ([IDCardNumber substringWithRange:NSMakeRange(1,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(11,1)].intValue) *9+ ([IDCardNumber substringWithRange:NSMakeRange(2,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(12,1)].intValue) *10+ ([IDCardNumber substringWithRange:NSMakeRange(3,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(13,1)].intValue) *5+ ([IDCardNumber substringWithRange:NSMakeRange(4,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(14,1)].intValue) *8+ ([IDCardNumber substringWithRange:NSMakeRange(5,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(15,1)].intValue) *4+ ([IDCardNumber substringWithRange:NSMakeRange(6,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(16,1)].intValue) *2+ [IDCardNumber substringWithRange:NSMakeRange(7,1)].intValue *1 + [IDCardNumber substringWithRange:NSMakeRange(8,1)].intValue *6+ [IDCardNumber substringWithRange:NSMakeRange(9,1)].intValue *3;NSInteger remainder = summary % 11;NSString *checkBit = @"";NSString *checkString = @"10X98765432";checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判断校验位
    
    return [checkBit isEqualToString:[[IDCardNumber substringWithRange:NSMakeRange(17,1)] uppercaseString]];
}


// 去掉UITextField空格字符
+(NSString *)deleteSpaceforTextField:(UITextField *)textfeild{
    return [textfeild.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}

//




//限制textField输入的文字
+(BOOL)limitTextFieldInputWord:(NSString *)string limitStr:(NSString *)limitStr
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:limitStr] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
    BOOL canChange = [string isEqualToString:filtered];
    return canChange;
}

//限制textField不能输入的字符
+(BOOL)limitTextFieldCanNotInputWord:(NSString *)string limitStr:(NSString *)limitStr
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:limitStr] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
    BOOL canChange = [string isEqualToString:filtered];
    return !canChange;
}

//保留2位小数
+(double)getTwoDecimalsDoubleValue:(double)number
{
 return round(number * 100.0)/100.0;
}


+(NSString *)getConcealPhoneNumber:(NSString *)phoneNum
{
    NSString *phoneStr=phoneNum;
    if (phoneStr!=nil) {
        //修改by chenli - 这里不用判断手机号是否有效
        if (phoneStr.length > 7) {
             phoneStr = [phoneStr stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        }
    }
    return phoneStr;
}

//判断输入的字符长度 一个汉字算2个字符
+ (NSUInteger)unicodeLengthOfString:(NSString *)text {
    NSUInteger asciiLength = 0;
    for(NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}

//字符串截到对应的长度包括中文 一个汉字算2个字符
+ (NSString *)subStringIncludeChinese:(NSString *)text ToLength:(NSUInteger)length{
    
    if (text==nil) {
        return text;
    }
    
    NSUInteger asciiLength = 0;
    NSUInteger location = 0;
    for(NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
        
        if (asciiLength==length) {
            location=i;
            break;
        }else if (asciiLength>length){
            location=i-1;
            break;
        }
        
    }
    
    if (asciiLength<length) { //文字长度小于限制长度
        return text;
        
    } else {
        
        __block NSMutableString * finalStr = [NSMutableString stringWithString:text];
        
        [text enumerateSubstringsInRange:NSMakeRange(0, [text length]) options:NSStringEnumerationByComposedCharacterSequences|NSStringEnumerationReverse usingBlock:
         ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
             
//             DLog(@"substring:%@ substringRange:%@  enclosingRange:%@",substring,NSStringFromRange(substringRange),NSStringFromRange(enclosingRange));
             
             if (substringRange.location<=location+1) {
                 NSString *temp=[text substringToIndex:substringRange.location];
                 finalStr=[NSMutableString stringWithString:temp];
                 *stop=YES;
             }
             
         }];

        return finalStr;
    }
}


+(void)limitIncludeChineseTextField:(UITextField *)textField Length:(NSUInteger)kMaxLength
{
    NSString *toBeString = textField.text;
    NSUInteger length = [self unicodeLengthOfString:toBeString];
    
    NSString *lang = [[textField textInputMode] primaryLanguage]; // 键盘输入模式
    //Bob iOS7后 使用[textField textInputMode] 替换了 [UITextInputMode currentInputMode]
    
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            
            if (length > kMaxLength) {
                
                textField.text = [self subStringIncludeChinese:toBeString ToLength:kMaxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        
        if (length > kMaxLength) {
            textField.text = [self subStringIncludeChinese:toBeString ToLength:kMaxLength];
        }
    }
}


//限制UITextField输入的长度，不包括汉字
+(void)limitTextField:(UITextField *)textField Length:(NSUInteger)kMaxLength
{
    NSString *toBeString = textField.text;
    if (toBeString.length > kMaxLength) {
        textField.text = [toBeString substringToIndex:kMaxLength];
    }
    
}

// [0-9a-zA-Z]{0,18}
//textField.text 输入之前的值 string 输入的字符
+ (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string andtype:(MyInputType )type
{
    NSString * kAlphaNum=nil;
    switch (type) {
        case MyInputTypeMIMA:
            kAlphaNum =@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            break;
        case MyInputTypeIDCARD:
            kAlphaNum =@"ＱＷＥＲＴＹＵＩＯＰＡＳＤＦＧＨＪＫＬＺＸＣＶＢＮＭｑｗｅｒｔｙｕｉｏｐａｓｄｆｇｈｊｋｌｚｘｃｖｂｎｍ（）０１２３４５６７８９qwertyuiopasdfghjklzxcvbnm()0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
            break;
        default:
            break;
    }
    
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    return canChange;
    
}
+(void)textField:(UITextField *)textField ChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL isHaveDian=NO;
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHaveDian = NO;
    }
    if ([string length] > 0) {
        
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确
            
            //首字母不能为0和小数点
            if([textField.text length] == 0){
                if(single == '.') {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                }
                if (single == '0') {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                }
                return;
            }
            
            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian = YES;

                }else{
    
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                }
            }else{
                if (isHaveDian) {//存在小数点
                    
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= 2) {
                      
                    }else{
                
                     
                    }
                }else{
                 
                }
            }
        }else{//输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
        }
    }

}


+ (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string Length:(NSUInteger)kMaxLength
{
    
    if ([string length] > 0) {
        
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确
            // 当前输入的字符是'.'
            if ([string isEqualToString:@"."]) {
                // 已输入的字符串中已经包含了'.'或者""
                if ([textField.text rangeOfString:@"."].location != NSNotFound || [textField.text isEqualToString:@""]) {
                    return NO;
                } else {
                    return YES;
                }
            } else {// 当前输入的不是'.'
                // 第一个字符是0时, 第二个不能再输入0
                if (textField.text.length == 1) {
                    unichar str = [textField.text characterAtIndex:0];
                    if (str == '0' && [string isEqualToString:@"0"]) {
                        return NO;
                    }
                }
                // 已输入的字符串中包含'.'
                if ([textField.text rangeOfString:@"."].location != NSNotFound) {
                    NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
                    [str insertString:string atIndex:range.location];
                    if (str.length >= [str rangeOfString:@"."].location + 4) {
                        return NO;
                    }
                    NSLog(@"str.length = %ld, str = %@, string.location = %ld", str.length, string, range.location);
                } else {
                    if (textField.text.length > kMaxLength-1) {
                        return range.location < kMaxLength;
                    }
                }
            }

        }else{
            return NO;
        }
    }
        return YES;
}




//用于限制UITextView的输入中英文限制
+(void)limitIncludeChineseTextView:(UITextView *)textview Length:(NSUInteger)kMaxLength
{
    NSString *toBeString = textview.text;
    NSUInteger length = [self unicodeLengthOfString:toBeString];
    
    NSString *lang = [[textview textInputMode] primaryLanguage]; // 键盘输入模式
    //Bob [UITextInputMode currentInputMode] isdepreted 使用 [textview textInputMode]
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textview markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textview positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            
            if (length > kMaxLength) {
                
                textview.text = [self subStringIncludeChinese:toBeString ToLength:kMaxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        
        if (length > kMaxLength) {
            textview.text = [self subStringIncludeChinese:toBeString ToLength:kMaxLength];
        }
    }
}

//限制UITextView输入的长度，不包括汉字
+(void)limitTextView:(UITextView *)textview Length:(NSUInteger)kMaxLength
{
    NSString *toBeString = textview.text;
    if (toBeString.length > kMaxLength) {
        textview.text = [toBeString substringToIndex:kMaxLength];
    }
    
}

//获得应用版本号
+(NSString *)getApplicationVersion
{
    //application version (use short version preferentially)
    NSString *applicationVersion=nil;
    applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if ([applicationVersion length] == 0)
    {
        applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
    }
    return applicationVersion;
}

//是否是纯数字 add卜增彦2014.11.11 不好用
+ (BOOL)isNumText:(NSString *)str
{
    NSString * regex        = @"(/^[0-9]*$/)";
    NSPredicate * pred      = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch            = [pred evaluateWithObject:str];
    if (isMatch)
    {
        return YES;
    }
    else
    {
        return NO;
    }
    

}

//是否是纯数字 
+ (BOOL)isPureInt:(NSString*)string
{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//add 首字符是否是英文开头
+ (BOOL)isEnglishFirst:(NSString *)string
{
    NSString *firstStr = [string substringToIndex:1];
    
    NSString *englishStr = @"^[a-zA-Z]+";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", englishStr];
    
    if ([predicate evaluateWithObject:firstStr])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//add 获取app名字
+ (NSString *)getApplicationName
{
    NSString *applicationName = nil;
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDictionary));
    applicationName = [infoDictionary objectForKey:@"CFBundleExecutable"];//CFBundleDisplayName
    
    return applicationName;
}
// 限制标点空格
+(BOOL)limitSpecialSting:(NSString *)string{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self beginswith %@ ",[string substringToIndex:1]];
    NSArray *symbolCharArray = @[@" ",@"·",@"~",@"!",@"@",@"#",@"$",@"%",@"^",@"&",@"*",@"(",@")",@"_",@"-",@"+",@"=",@"{",@"[",@"}",@"]",@"|",@"、",@"：",@"；",@"“",@"‘",@"《",@"，",@"》",@"。",@"？",@"、",@"<",@">",@"."];
    NSArray *resultArray = [symbolCharArray filteredArrayUsingPredicate:predicate];
    if (resultArray.count>0) {
        return YES;
    }else
        return NO;
    
}


#pragma mark - 倒计时按钮
// 开启倒计时效果
+(void)openCountdown:(UIButton *)authCodeBtn{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [authCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [authCodeBtn setTitleColor:[UIColor add_colorWithRGBHexString:@"424242"] forState:UIControlStateNormal];
                authCodeBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [authCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                [authCodeBtn setTitleColor:[UIColor add_colorWithRGBHexString:@"979797"] forState:UIControlStateNormal];
                authCodeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


#pragma mark - 创建二维码 图片
+ (UIImageView *)generatedQRCodeWithStr:(NSString *)str {
    //二维码滤镜
    CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
    //恢复滤镜的默认属性
    [filter setDefaults];
    //将字符串转换成NSData
    NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
    //通过KVO设置滤镜inputmessage数据
    [filter setValue:data forKey:@"inputMessage"];
    //获得滤镜输出的图像
    CIImage *outputImage=[filter outputImage];
    UIImageView *imageView = [[UIImageView alloc] init];
    //将CIImage转换成UIImage,并放大显示
    imageView.image=[Util createNonInterpolatedUIImageFormCIImage:outputImage withSize:100.0];
    //如果还想加上阴影，就在ImageView的Layer上使用下面代码添加阴影
    imageView.layer.shadowOffset=CGSizeMake(0, 0.5);//设置阴影的偏移量
    imageView.layer.shadowRadius=1;//设置阴影的半径
    imageView.layer.shadowColor=[UIColor blackColor].CGColor;//设置阴影的颜色为黑色
    imageView.layer.shadowOpacity=0.3;
    return imageView;
}
//改变二维码大小

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGColorSpaceRelease(cs);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    UIImage *tempImage = [UIImage imageWithCGImage:scaledImage];
    CGImageRelease(scaledImage);
    return tempImage;
    
}

//保存图片
+ (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

+ (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    if (!error) {
       // 保存成功 弹框
    }
}



#pragma mark - 快捷获取 与 调用

+(NSString *)deviceTokenString
{
    return ZXNotificationManage.deviceToken;
}


+(void)invokeVibration
{
    //TODO: 振动调用
    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}

+(void)showAppCommentWithAppID:(int)appID
{
    NSString *appId = @"";
    //显示AppStore应用评论
    NSURL *appUrlStr = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",appId]];
    
    [[UIApplication sharedApplication] openURL:appUrlStr];
}

+ (void)callAtOnce:(NSString *)telephoneNum
{
    NSString *str = [NSString stringWithFormat:@"tel://%@", telephoneNum];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

+(void)callOpenUrl:(NSString *)telephoneNum{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",telephoneNum];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
+ (void)sendSMS:(NSString *)telephoneNum
{
    NSString *str = [NSString stringWithFormat:@"sms://%@", telephoneNum];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

+ (void)sendEmail:(NSString *)emailAddr
{
    NSString *str = [NSString stringWithFormat:@"mailto://%@", emailAddr];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

+ (void)openUrl:(NSString *)url
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    });
}

+(NSStringEncoding)getGBKEncoding
{
    //获得中文gbk编码
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    return enc;
}

+ (NSString *)getAvatarFilePath
{
    NSString *avatarFileName = [NSString stringWithFormat:@"userAvatar.png"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,
                                                         NSUserDomainMask,
                                                         YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:avatarFileName];
}

//设置状态栏颜色
+ (void)statusWithStyle:(UIStatusBarStyle)style
{
    [[UIApplication sharedApplication] setStatusBarStyle:style];
}




#pragma mark -- 相机权限 --
+ (BOOL)isHaveCameraShowTips:(BOOL)show
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        return YES;
    }
    else{
        if (show) {
            [Util createAlertViewWithMessage:Alertno_camera];
        }
        return NO;
    }
}

+ (BOOL)isCameraAccessShowTips:(BOOL)show // 显示弹框
{
    if (![Util isHaveCameraShowTips:show]){
        return NO;
    }
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
    {
        if (show)
        {
            [Util createAlertViewWithTitle:Alert_TIPS message:Alert_have_no_cameraAccess cancel:Aler_Title_CANCEL sure:Aler_Title_SURE tag:k_Camera_Tag_Key delegate:[Util sharedUIFactory]];
            
        }
        return NO;
    }
    else{
        return YES;
    }
}

+ (BOOL)isAssetsLibraryAccessShowTips:(BOOL)show
{
    if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 8 )) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted ||
            status == PHAuthorizationStatusDenied) {
            return NO;
        }
        return YES;
    }else{
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if(author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied)
        {
            if (show)
            {
                [Util createAlertViewWithTitle:Alert_TIPS message:Alert_have_no_libraryAccess cancel:Aler_Title_CANCEL sure:Aler_Title_SURE tag:k_Photo_Libary_Tag_Key delegate:[Util sharedUIFactory]];
                //进入设置
            }
            return NO;
        }
        else{
            return YES;
        }
    }

}

+ (void)go2AppAuthorizationSettting {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

+ (void)go2SystemCameraAuthorizationSetting
{
    if (IOS8_OR_LATER) {
        [self go2AppAuthorizationSettting];
    }
    else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]];
    }
}

+ (void)go2SystemLibraryAuthorizationSetting
{
    if (IOS8_OR_LATER) {
        [self go2AppAuthorizationSettting];
    }
    else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]];
    }
}

+ (void)go2SystemLocationServicesSetting {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
}

+ (void)autoGo2LocationServicesSetting {
    if (IOS8_OR_LATER) {
        [self go2AppAuthorizationSettting];
    }
    else {
        [self go2SystemLocationServicesSetting];
    }
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        if (alertView.tag == k_Camera_Tag_Key) {
            [[self class] go2SystemCameraAuthorizationSetting];
        }
        else if (alertView.tag == k_Photo_Libary_Tag_Key) {
            [[self class] go2SystemLibraryAuthorizationSetting];
        }
    }
}

// 消息通知是否开启
+ (BOOL)isMessageNotificationServiceOpen{
    //iOS8 check if user allow notification
       if (IOS8_OR_LATER) {// system is iOS8
           
            UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
            if (UIUserNotificationTypeNone != setting.types) {
                       return YES;
            }
        } else {//iOS7
                UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
            if(UIRemoteNotificationTypeNone != type)
                             return YES;
       }
    
    return NO;
    
}
+(void)autoGo2NotificationsSetting{
    if (IOS8_OR_LATER) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=NOTIFICATIONS_ID"]];
    }
}




#pragma mark --  JSON 解析 --

/***** json *****/
+ (id)jsonWithData:(NSData *)data error:(NSError **)error
{
    NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:error];
    return jsonDic;
}

//对象转 jsonData
+ (NSData *)jsonDataWithObject:(id)data error:(NSError **)error
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:error];
    return jsonData;
}

+ (NSString *)jsonStringWithObject:(id)data error:(NSError **)error
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:error];
    NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return string;
}

// 没网取缓存 有都是最新的
//+ (NSMutableURLRequest *)loadDataformUrl:(NSURL *)URL{
//    if ([Reachability networkAvailable]) {
//        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];        return request;
//    }else{
//        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0f];
//        return request;
//    }
//}



#pragma mark - maskBorderAndRadiu
+(void)maskBorderAndRadiu:(UIView *)maskView
{
    [[self class] maskBorderAndRadiu:maskView color:maskView.backgroundColor cornerRadius:7.0 borderWidth:0];
}

+(void)maskBorderAndRadiu:(UIView *)maskView borderColor:(UIColor *)borderColor
{
    [[self class] maskBorderAndRadiu:maskView color:borderColor cornerRadius:5.0 borderWidth:1];
}

+(void)maskBorderAndRadiu:(UIView *)maskView color:(UIColor *)color cornerRadius:(CGFloat)cornerRadius borderWidth:(CGFloat)borderWidth
{
    if(borderWidth > 0) {
        maskView.layer.borderColor   = color.CGColor;
        maskView.layer.borderWidth   = borderWidth;
    }
    maskView.layer.cornerRadius  = cornerRadius;
    
    maskView.layer.masksToBounds = YES;
}



#pragma mark - 通过枚举获取字符串

+(NSString *)getMGAuthenticationStatus:(MGAuthenticationStatus )Status{

    if (Status==MGAuthenticationStatusNo) {
         return @"未认证";
    }else if (Status==MGAuthenticationStatusOk){
         return @"认证通过";
    }else if (Status==MGAuthenticationStatusFail){
        return @"认证失败";
    }else{
         return @"等待审核";
    }
    
    
}

+(NSString *)getMGOfficestatus:(MGOfficestatus )Status{
    // 0.查询失败1.办理中2.待缴税费3.已办结4.已归档5.原件退回6.办理之中（待缴税费）7.已办结（作废）
  
    if (Status==MGOfficestatusFail) {
        return @"查询失败";
    }else if (Status==MGOfficestatusIng){
        return @"办理中";
    }else if (Status==MGOfficestatusWaitingTaxFees){
        return @"待缴税费";
    }else if (Status==MGOfficestatusDid){
        return @"已办结";
    }else if (Status==MGOfficestatusDidArchive){
        return @"已归档";
    }else if (Status==MGOfficestatusBackToTheOriginal){
        return @"原件退回";
    }else if (Status==MGOfficestatusDealtEWithIn){
        return @"办理之中（待缴税费）";
    }
    else{
        return @"已办结（作废）";
    }
   
}
+(NSString *)getMGConsultFileStatus:(MGConsultFileStatus )Status{
   
    
    if (Status==MGConsultFileStatusDiYaChaFeng) {
        return @"抵押查封";
    }else if (Status==MGConsultFileStatusYouXiao){
        return @"有效";
    }else if (Status==MGConsultFileStatusWuXiao){
        return @"无效";
    }else if (Status==MGConsultFileStatusChaFeng){
        return @"查封";
    }else if (Status==MGConsultFileStatusDiYa){
        return @"抵押";
    }else{
        return @"无效";
    }
    
}

+(NSString *)getMGConsultFileDealStatus:(MGConsultFileDealStatus )Status
{
    if (Status==MGConsultFiledealStatusNO) {
        return @"未处理";
    }else if (Status==MGConsultFiledealStatusSuccss){
        return @"处理成功";
    }else if (Status==MGConsultFiledealStatusIng){
        return @"正在处理中";
    }else if (Status==MGConsultFiledealStatusFail){
        return @"查询失败";
    }else if (Status==MGConsultFiledealStatusError){
        return @"系统错误";
    }else if (Status==MGConsultFiledealStatusAutoIng){
        return @"自动处理中";
    }else if (Status==MGConsultFiledealStatusRequstFail){
        return @"请求失败";
    }else{
        return @"请求中";
    }

}

@end
